module ActiveRecord
  module ConnectionAdapters
    class TableDefinition
      def userstamps
        column(:created_by, :integer)
        column(:updated_by, :integer)
      end
    end
  end
end

module Stonean
  module MysqlUtils
    def add_foreign_key(from_table, to_table, is_required = false)
      col_name = to_table.to_s.singularize + "_id"

			ops = {}
			ops = {:null => false} if is_required

			add_column(from_table, col_name, :integer, ops)

      define_foreign_key_column(from_table, col_name, to_table)
    end

    def remove_foreign_key(from_table, to_table)
      col_name = to_table.to_s.singularize + "_id"
      execute("alter table #{from_table} drop foreign key fk_#{from_table}_#{col_name}")
      remove_column(from_table, col_name)
    end

    def remove_foreign_key_column(from_table, col_name)
      execute("alter table #{from_table} drop foreign key fk_#{from_table}_#{col_name}")
      remove_column(from_table, col_name)
    end
  
    def define_foreign_key_column(from_table, from_column, to_table, to_column = "id")
      constraint_name = "fk_#{from_table}_#{from_column}"

      sql = <<-SQL
        alter table #{from_table} add constraint #{constraint_name}
        foreign key (#{from_column})
          references #{to_table}(#{to_column})
      SQL

      execute(sql)
    end

    def create_join_table(table_one, table_two, fk = true)
      c1 = "#{table_one.to_s.singularize}_id"
      c2 = "#{table_two.to_s.singularize}_id"
      lt =  "#{table_one}_#{table_two}"

      create_table(lt, :id => false) do |t|
        t.column c1, :integer, :null => false
        t.column c2, :integer, :null => false
      end

      pkey = "alter table #{lt} add primary key (#{c1}, #{c2})"
      execute(pkey)

      if fk
        define_foreign_key_column(lt, c1, table_one)
        define_foreign_key_column(lt, c2, table_two)
      end
    end

    def drop_join_table(table_one, table_two)
      drop_table("#{table_one}_#{table_two}")
    end

    def create_reference_table(tname, *referenced_by)
      create_table(tname) do |t|
        t.column(:name, :string)
      end

      referenced_by.each do |rtable|
        add_foreign_key(rtable, tname)
      end
    end

    def drop_reference_table(tname, *referenced_by)
      referenced_by.each do |rtable|
        remove_foreign_key(rtable, tname)
      end

      drop_table(tname)
    end

	  def add_fulltext_key(table, name, cols)
      sql = <<-SQL
        alter table #{table} add fulltext #{name} (#{cols.join(",")})
      SQL
      execute(sql)
    end

  end#MigrationUtils
end # module Stonean

ActiveRecord::Migration.send :extend, Stonean::MysqlUtils


